'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 全局BOSS
 * @author sundbcn@gmail.com (sun debing)
 */

var moment = require('moment');
var mongoConnector = require('../libs/mongodb/mongoConnector');
/* jshint unused:false */
var globalBossSchema = require('../schemas/globalBossSchema');
var GlobalBoss = mongoConnector().model('GlobalBoss');
var bossConf = require('../config/bossConf.js');

/**
 * 添加记录
 */
module.exports.create = function (boss_id, refresh_tm, cb) {
    // 创建成功后
    var afterCreate = function (err, model) {
        cb(err, model);
    };

    GlobalBoss.create({
        boss_id: boss_id,
        refresh_tm: refresh_tm
    }, afterCreate);
};

/**
 * 查询全局BOSS信息
 * @param  {[type]}   order_id [description]
 * @param  {Function} cb       [description]
 * @return {[type]}            [description]
 */
module.exports.getGlobalBossInfo = function (cb) {
    var self = this;
    var afterFound = function (err, model) {
        var this_day = moment().startOf('day').unix();
        var boss_id;
        if (!model) {
            boss_id = bossConf.getRandBossId();
            return self.create(boss_id, this_day, cb);
        }

        if (this_day > model.refresh_tm) {
            // 新的一天开始，随机出新的BOSS
            boss_id = bossConf.getRandBossId();
            var where = {
                refresh_tm: {
                    $lt: this_day
                }
            };
            var values = {
                boss_id: boss_id,
                refresh_tm: this_day
            };
            GlobalBoss.update(where, values).exec(function (err, effect) {
                GlobalBoss.findOne({}, cb);
            });
        } else {
            cb(err, model);
        }
    };

    GlobalBoss.findOne({}, afterFound);
};
